import { getUserInfo, loginAPI, loginOutAPI } from '@/apis/user'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getToken, removeToken, setToken } from '@/utils/token'
import { routes ,asyncRoute,anyRoute} from '@/router/route'
import { RouteRecordRaw } from 'vue-router'
import { loginParams, loginRes, userInfoRes } from '@/types/user'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
//定义过滤当前用户需要展示的路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

export const useUserStore = defineStore('user', () => {
  //定义token
  const token = ref<string | null>(getToken() || '')
  //定义路由
  const menuRoutes = ref<RouteRecordRaw[]>(routes)
  //定义用户信息
  const username = ref('')
  const avatar = ref('')
  //用户是否包含按钮
  const buttons=ref<string[]>([])

  //用户登录
  const login = async (data: loginParams) => {
    const result: loginRes = await loginAPI(data)
    if (result.code == 200) {
      token.value = result.data as string
      //本地存储持久化存储一份
      setToken(result.data as string)
      //能保证当前async函数返回一个成功的promise
      return 'ok'
    } else {
      return Promise.reject(new Error(result.data))
    }
  }

  //退出登录
  const loginOut = async () => {
    const result: any = await loginOutAPI()
    if (result.code == 200) {
      ;(username. value = ''), (avatar.value = '')
      ;(token.value = ''), removeToken()
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }

  //获取用户信息
  const getUser = async () => {
    const result:userInfoRes = await getUserInfo()
    if (result.code == 200) {
      username.value = result.data.name
      avatar.value = result.data.avatar
      buttons.value=result.data.buttons
      //计算当前用户需要展示的路由
      const userAsyncRoute = filterAsyncRoute(
        cloneDeep(asyncRoute),
        result.data.routes,
      )
      menuRoutes.value=[...routes,...userAsyncRoute,anyRoute];
      //用户展示的异步路由
      [...userAsyncRoute, anyRoute].forEach((route: any) => {
        router.addRoute(route)
      })
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }
  //清除用户信息
  //导出
  return {
    buttons,
    token,
    login,
    menuRoutes,
    username,
    avatar,
    getUser,
    loginOut,
  }
})
